import json
import math
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views import View
from app.models import UserProfile


class ChangeUserView(View):
    def get(self, request):
        try:
            # 获取百分比
            my_id = request.GET.get('my_id')
            if not my_id:
                return JsonResponse({
                    "code": "422",  # 状态码
                    "msg": "缺少my_id",  # 消息
                }, safe=False)
            user_list = UserProfile.objects.get(id=my_id)  # 根据用户id查询用户信息
            data = model_to_dict(user_list)
            empty_fields = 0
            all_fields = 0
            for key, value in data.items():
                if value is None or value == '' or value == 'undefined':
                    empty_fields += 1  # 为空的数据
                all_fields += 1  # 所有的数据
            non_empty_fields = all_fields - empty_fields
            non_empty_percentage = (non_empty_fields / all_fields) * 100
            non_empty_percentage_floor = math.floor(non_empty_percentage)  # 向下取整
            return JsonResponse({
                "code": "200",  # 状态码
                "msg": "请求成功",  # 消息
                "data": non_empty_percentage_floor
            }, safe=False)
        except Exception as e:
            return JsonResponse({
                "code": 500,
                "msg": str(e)
            })

    def post(self, request):
        try:
            # 添加或者修改用户信息
            if not request.body:
                return JsonResponse({
                    "code": 422,
                    "msg": "缺少参数"
                })
            data = json.loads(request.body)  # 获取请求数据
            # 如果有my_id说明为修改，那么将直接修改用户信息
            if data.get('my_id'):
                user_profile = get_object_or_404(UserProfile, id=data.get('my_id'))
            else:
                user_profile = UserProfile()
            # 遍历POST数据并赋值给UserProfile实例
            for key, value in data.items():
                if hasattr(user_profile, key) and key != 'my_id':
                    setattr(user_profile, key, value)
            user_profile.save()
            return JsonResponse({"code": 200})
        except Exception as e:
            return JsonResponse({
                "code": 500,
                "msg": str(e)
            })
